package com.sziit.DBTools;


import java.sql.*;

public class DButil {

    //数据库连接对象
    protected Connection conn;
    //sql执行对象
    protected PreparedStatement prep;
    //返回结果对象
    protected ResultSet rs;

    /**
     * Function: 创建数据库连接
     * Date: 2019/10/12 14:26
     * Notice:
     **/
    public boolean getConnection(){
        //配置信息，配置ip、端口、用户名、密码
        String driver="com.mysql.cj.jdbc.Driver";
        String url="jdbc:mysql://119.23.242.119:3306/my-db?serverTimezone=UTC&characterEncoding=utf8&useSSL=true";
        String user="public";
        String password="123456";

        //加载JDBC驱动
        try {
            Class.forName(driver);
            conn= DriverManager.getConnection(url, user, password);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return false;
        }
        return true;
    }


    /**
     * Function: 关闭资源
     * Date: 2019/10/12 14:34
     * Notice:
     **/
    public boolean closeResource(){
        try {
            if (rs != null) {
                rs.close();
            }

            if (prep != null) {
                prep.close();
            }

            if (conn != null) {
                conn.close();
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    /**
     * Function: 添加记录
     * Date: 2019/10/12 14:35
     * Notice:
     **/
    public int updateData(String sql,Object[] params){
        int updateRows=0;
        if(getConnection()){
            try {
                prep=conn.prepareStatement(sql);
                //填充占位符
                for(int i=0; i<params.length; i++){
                    prep.setObject(i+1, params[i]);
                }
                updateRows=prep.executeUpdate();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return updateRows;
    }

    /**
     * Function: 查询记录
     * Date: 2019/10/12 14:35
     * Notice:
     **/
    public ResultSet searchData(String sql,Object[] params){
        if(getConnection()){
            try {
                prep=conn.prepareStatement(sql);
                for (int i = 0; i < params.length; i++) {
                    prep.setObject(i+1,params[i]);
                }
                rs=prep.executeQuery();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return rs;
    }
}
